package com.iretailer.report.web.report;

import com.iretailer.report.base.BaseAction;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.report.ReFace;
import com.iretailer.report.model.GenderAgeImage;
import com.iretailer.report.util.ImageBase64;
import com.iretailer.report.util.RMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/8/12 0012 10:49
 * @Description:
 */
@RestController
public class FaceController extends BaseAction {
    private static final Logger log = LoggerFactory.getLogger(ReportController.class);

    @RequestMapping("/report/faceGrid.action")
    public Map<String, Object> faceGrid(@RequestBody ReFace reFace) {
        QueryOption queryOption = modelMapper.map(reFace, QueryOption.class);
        PageResult<GenderAgeImage> result = faceService.faceImageGrid(reFace.getDids(), reFace.getStartDate(), reFace.getEndDate(), queryOption);
        return RMap.ok(result);
    }

    @RequestMapping("/report/lastFaceGrid.action")
    public Map<String, Object> lastFaceGrid(@RequestBody ReFace reFace) {
        QueryOption queryOption = modelMapper.map(reFace, QueryOption.class);
        PageResult<GenderAgeImage> result = faceService.lasetFaceImageGrid(reFace.getMallId(), reFace.getStartDate(), reFace.getEndDate(), queryOption);
        return RMap.ok(result);
    }

    @RequestMapping("/report/lastFaceDetailGrid.action")
    public Map<String, Object> faceMatchDetailGrid(@RequestBody ReFace reFace) {
        QueryOption queryOption = modelMapper.map(reFace, QueryOption.class);
        PageResult<GenderAgeImage> result = faceService.lastFaceImageDetailGrid(reFace.getPersonId(), reFace.getStartDate(), reFace.getEndDate(), queryOption);
        return RMap.ok(result);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/report/{imageId}/getFaceImage.action")
    public void getFaceImage(@PathVariable("imageId") String imageId, HttpServletResponse response) {
        log.error(imageId);
        String img = faceService.getFaceImage(imageId);
        OutputStream os = null;
        try {
            response.setContentType("image/png");
            os = response.getOutputStream();
            byte[] bytes = ImageBase64.generateImage(img);
            os.write(bytes);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
